﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.SFA.Server.BusinessRule.System;
using Jumpton.SFA.Server.Entity;

public partial class System_Organization : PageBase
{
    OrgainzationManager orgManager = new OrgainzationManager();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindTree();
            BindRegion(null,null,false);
   //         imgSearch.Attributes.Add("onclick", "openPopup('../System/PopupOrganization.aspx?NameControlId=" + txtParentOrg.UniqueID + "&ValueControlId=" + txtHidOrg.UniqueID + "&SelectType=single','','300','500');");
        }
    }

    private void BindRegion(int? ParentID, String CurrentOrgLevel, Boolean IsAdd)
    {
        ddlDistrict.Enabled = true;
        ddlState.Enabled = true;
        ddlCity.Enabled = true;
        ddlCountry.Enabled = true;
        var countries = new RegionManager().GetRegionDistinctData(MyStateManager.DomainID, 0, null);
        ddlCountry.DataSource = countries;
        ddlCountry.DataBind();
        if (countries != null && countries.Rows.Count > 0)
        {
            ddlState.DataSource = new RegionManager().GetRegionDistinctData(MyStateManager.DomainID, 1, countries.Rows[0]["COUNTRY_CODE"].ToString());
            ddlState.DataBind();
        }
        ddlState.Items.Insert(0, new ListItem("全部", null));
        ddlCity.Items.Clear();
        ddlCity.Items.Insert(0, new ListItem("全部", null));
        ddlDistrict.Items.Clear();
        ddlDistrict.Items.Insert(0, new ListItem("全部", null));

        if (ParentID != null)
        {
            var org = orgManager.Load(ParentID.Value);
            try
            {
                //判断节点长度
                String level = org.ORGLEVEL.ToString();
                if (level.Length >= 2)
                {
                    int l;
                    if (int.TryParse(level.Substring(0, 2), out l))
                    {
                        //this.RegionOnSelectedIndexChanged(ddlCountry, EventArgs.Empty);
                        ddlState.SelectedValue = level.Substring(0, 2);
                        this.RegionOnSelectedIndexChanged(ddlState, EventArgs.Empty);
                        ddlState.Enabled = false;
                        if (org.ORGLEVEL == CurrentOrgLevel) 
                        {
                            ddlState.Enabled = false;
                        }
                    }

                    ddlCountry.Enabled = false;

                }
                if (level.Length == 2 && CurrentOrgLevel.Length == 2)
                {
                    ddlState.SelectedValue = CurrentOrgLevel.Substring(0, 2);
                    this.RegionOnSelectedIndexChanged(ddlState, EventArgs.Empty);
                    if (IsAdd)
                        ddlState.Enabled = false;
                    else
                    {
                        if (org.ORGLEVEL == CurrentOrgLevel)
                        {
                            ddlState.Enabled = false;
                        }else
                            ddlState.Enabled = true;

                    }
                        
                }

                if (level.Length >= 4)
                {

                    ddlCity.SelectedValue = level.Substring(0, 4);
                    this.RegionOnSelectedIndexChanged(ddlCity, EventArgs.Empty);
                    if (IsAdd)
                    {
                        ddlCity.Enabled = false;
                    }
                    else
                    {
                        if (org.ORGLEVEL == CurrentOrgLevel)
                        {
                            ddlCity.Enabled = false;
                        }
                        else
                            ddlCity.Enabled = true;
                    }
                    
                }
                else if (level.Length > 2 && level.Length<4)
                {
                    if (IsAdd)
                        ddlState.Enabled = false;
                    else
                    {
                        if (org.ORGLEVEL == CurrentOrgLevel)
                        {
                            ddlState.Enabled = false;
                        }
                        else
                            ddlState.Enabled = true;
                    }
                    ddlState.SelectedValue = CurrentOrgLevel.Substring(0, 2);
                    this.RegionOnSelectedIndexChanged(ddlState, EventArgs.Empty);
                }
                if (level.Length >= 6)
                {
                    ddlDistrict.SelectedValue = level.Substring(0, 6);
                    this.RegionOnSelectedIndexChanged(ddlDistrict, EventArgs.Empty);
                    ddlDistrict.Enabled = false;
                }
                else
                {
                    if (IsAdd && CurrentOrgLevel.Length == 4)
                        ddlCity.Enabled = false;
                    ddlCity.SelectedValue = CurrentOrgLevel.Substring(0, 4);
                    this.RegionOnSelectedIndexChanged(ddlCity, EventArgs.Empty);
                   
                }
                if (CurrentOrgLevel.Length == 6)
                {
                    if(IsAdd)
                        ddlDistrict.Enabled = false; 
                    ddlDistrict.SelectedValue = CurrentOrgLevel.Substring(0, 6); 
                }
            }
            catch(Exception ex)
            {
            }
        }
    }

    protected void RegionOnSelectedIndexChanged(object sender, EventArgs e)
    {
        if (sender == ddlCountry)
        {
            ddlState.DataSource = new RegionManager().GetRegionDistinctData(MyStateManager.DomainID, 1, ddlCountry.SelectedValue);
            ddlState.DataBind();
            ddlState.Items.Insert(0, new ListItem("全部", null));
            RegionOnSelectedIndexChanged(ddlState, e);
        }
        else if (sender == ddlState)
        {
            ddlCity.DataSource = new RegionManager().GetRegionDistinctData(MyStateManager.DomainID, 2, ddlState.SelectedValue);
            ddlCity.DataBind();
            ddlCity.Items.Insert(0, new ListItem("全部", null));
            RegionOnSelectedIndexChanged(ddlCity, e);
        }
        else if (sender == ddlCity)
        {
            ddlDistrict.DataSource = new RegionManager().GetRegionDistinctData(MyStateManager.DomainID, 3, ddlCity.SelectedValue);
            ddlDistrict.DataBind();
            ddlDistrict.Items.Insert(0, new ListItem("全部", null));
        }
        
    }

    private void FillForm()
    {
        rdRight.Visible = true;
        //判断右边是新增还是编辑页面加载

        ORGANIZATION org = orgManager.Load(int.Parse(TreeOrg.SelectedValue));
        
        //新增
        if (rdoAdd.Checked)
        {
            txtOrgName.Text = txtRemark.Value = string.Empty;
            //加载所有的部门数据 
            chkStatus.Checked = true;
            txtParentOrg.Text = org.NAME;
            BindRegion(org.ParentID, org.ORGLEVEL,true);
        }
        else
        {
            BindRegion(org.ParentID, org.ORGLEVEL, false);
            //if (TreeOrg.SelectedNode.Depth == 0)
            //{
            //    imgSearch.Visible = false;
            //}

            //获取上一级的ORG
            ORGANIZATION parentOrg = orgManager.Load(org.ParentID);
            try
            {
                txtParentOrg.Text = parentOrg.NAME;
                ViewState["PARENTID"] = parentOrg.ID;
            }
            catch
            {
            }
            txtOrgName.Text = org.NAME;
            txtRemark.Value = org.REMARK;
          
            chkStatus.Checked = org.ACTIVE;

        }
    }

    private void BindTree()
    {
        TreeOrg.Nodes.Clear();
        DataTable dt = orgManager.SearchOrgTree(MyStateManager.DomainID, MyStateManager.OrgID, null);
        DataRow[] rows = dt.Select("level=1");
        foreach (DataRow row in rows)
        {
            TreeNode node = new TreeNode();

            node.Value = row["id"].ToString();
            if (row["ACTIVE"].ToString() == "0")
            {
                node.Text = string.Format("<span style=\"color:red\">{0} (已禁用)</span>", row["name"].ToString());
            }
            else
                node.Text = row["name"].ToString();
            AddSubNode(node, dt);
            TreeOrg.Nodes.Add(node);
        }
        TreeOrg.CollapseAll();

    }

    private void AddSubNode(TreeNode node, DataTable dt)
    {
        DataRow[] rows = dt.Select("parentid=" + node.Value);
        foreach (DataRow row in rows)
        {
            TreeNode ChildNode = new TreeNode();
            if (row["ACTIVE"].ToString() == "0")
            {
                ChildNode.Text = string.Format("<span style=\"color:red\">{0} (已禁用)</span>", row["name"].ToString());
            }
            else
                ChildNode.Text = row["name"].ToString();
            ChildNode.Value = row["id"].ToString();
            AddSubNode(ChildNode, dt);
            node.ChildNodes.Add(ChildNode);
        }
    }
    protected void TreeOrg_SelectedNodeChanged(object sender, EventArgs e)
    {
        TreeNode selectedNode = TreeOrg.SelectedNode;

        //如果没有选择节点，返回
        if (selectedNode == null)
            return;

        if (selectedNode.Value != "-1")
        {
            FillForm();
        }

    }
   

    protected void btnSave_Click(object sender, EventArgs e)
    {
    
        ORGANIZATION org;
        //判断是新增还是保存
        if (rdoAdd.Checked)
        {
            org = new ORGANIZATION();
            org.ParentID = int.Parse(TreeOrg.SelectedValue);

        }
        else
        {
            org = orgManager.Load(int.Parse(TreeOrg.SelectedValue));
            int parentID = int.Parse(ViewState["PARENTID"].ToString());

            //判断所选的上级是否包含本组织以及子级
            DataTable dt = orgManager.SearchOrgTree(MyStateManager.DomainID, org.ID, null);

            if (dt.Select("id='" + parentID + "'").Length > 0)
            {
                ShowMessage("上级组织不能包含本组织以及以下的组织");
                return;
            }

            org.ParentID = parentID;
        }
     
        org.NAME = txtOrgName.Text.Trim();
        String level = null;
        if (ddlState.SelectedIndex == 0)
        {
            level = ddlCountry.SelectedValue;
        }
        else if (ddlCity.SelectedIndex == 0)
        {
            level = ddlState.SelectedValue;
        }
        else if (ddlDistrict.SelectedIndex == 0)
        {
            level = ddlCity.SelectedValue;
        }
        else
        {
            level = ddlDistrict.SelectedValue;
        }
        org.ORGLEVEL = level;
        org.ACTIVE = chkStatus.Checked;
        org.DOMAINID = MyStateManager.DomainID;
        org.REMARK = txtRemark.Value;
        org.LAST_UPDATE_TIME = BusinessLogic.GetDateTimeDecimal(DateTime.Now);
        org.LAST_UPDATER = MyStateManager.Name;

        //如果置为无效则所以子结点都无效
        if (!org.ACTIVE)
            orgManager.DisabledChildOrgs(MyStateManager.DomainID, org.ID);

        //保存本次操作
        string result = orgManager.Save(org);



        if (result != string.Empty)
            ShowMessage(result);
        else
            BindTree();


    }
    protected void rdoAdd_CheckedChanged(object sender, EventArgs e)
    {
        FillForm();
    }

}
